package com.caiyi.financial.nirvana.sms.queue;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.entity.SmsReceiveMessage;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.service.SmsReceiveMessageService;
import com.caiyi.financial.nirvana.sms.task.PushReceiveTask;
import com.caiyi.financial.nirvana.sms.util.ThreadPoolUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 上行入库
 */
@Component
public class ReceiveMessageQueue implements IRedisQueue {

    public static final Logger logger = LoggerFactory.getLogger(ReceiveMessageQueue.class);
    private static final int MAX_CACHE_SIZE = 100;
    private static final int INSERT_INTERVAL = 3 * 1000;
    private final List<SmsReceiveMessage> cache = new ArrayList<>();
    private long startTime = System.currentTimeMillis();
    @Autowired
    private SmsReceiveMessageService smsReceiveMessageService;

    @Override
    public String key() {
        return JedisKey.SMS_QUEUE_RECEIVE_MESSAGE_DB;
    }

    public void run(List<String> list) {
        if (list != null && !list.isEmpty()) {
            SmsReceiveMessage entity = JSON.parseObject(list.get(1), SmsReceiveMessage.class);
            //Modified by zhaojie 20180316 过滤emoji表情字符
            entity.setContent(entity.getContent().replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]+", ""));
            entity.setCreateTime(new Date());
            entity.setUpdateTime(new Date());
            cache.add(entity);
            if (StringUtils.isNotBlank(entity.getAccount())){
                //上行客户回调 Added by zhaojie 20180312
                PushReceiveTask task = new PushReceiveTask(entity);
                ThreadPoolUtil.EXECUTOR_PUSH_MESSAGE.execute(task);
            }
        }
        boolean batch = this.cache.size() == MAX_CACHE_SIZE || (System.currentTimeMillis() - startTime) > INSERT_INTERVAL;
        batch = batch && cache.size() > 0;
        if (batch) {
            //开始插入
            smsReceiveMessageService.insertList(this.cache);
            //清空缓存
            cache.clear();
            //重置时间
            startTime = System.currentTimeMillis();
            logger.info("ReceiveMessageQueue insertList size : {} , insertList clear", this.cache.size());
        }
    }

    @Override
    public void interrupt(Exception e) {

    }

}
